package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.*;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

/**
 * 山东快乐扑克3 官方开奖结果抓取
 * 地址: http://www3.sdticai.com/find/find_klpk.asp?Page=1
 * @author zhangzq
 *
 */
public class LotteryDrawFetch567WorkerOfficial extends AbstractLotteryDrawFetchWorker {

    private final static String URL_HISTORY = "http://www3.sdticai.com/find/find_klpk.asp?Page=1";

	public LotteryDrawFetch567WorkerOfficial() {
		super(LotteryType.SDKLPK3);
	}

	@Override
	public LotteryDraw fetchResultDetail(String phase) {
        if (phase == null || "".equals(phase)) {
            logger.error("传入的彩期为空！");
            return null;
        }
        LotteryType lotteryType = this.getLotteryType();
        String fetchUrl = this.getResultDetailUrl(phase);
        if (StringUtils.isEmpty(fetchUrl)) {
            logger.error("==详细页面==抓取=={}==期号：{}==详细地址不存在，返回null", lotteryType.getName(), phase);
            return null;
        }
        String data;
        Parser parser;
        try {
            data = CoreFetcherUtils.URLGet(fetchUrl, null, CharsetConstant.CHARSET_GBK);
        } catch (Exception e) {
            logger.error("获取html数据失败" + e.getMessage());
            return null;
        }
        try {
            parser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("解析html出错, data={}", data);
            return null;
        }
        String tempPhase = phase.substring(2);
        NodeFilter filterPhase = new RegexFilter(tempPhase);
        NodeFilter filterHasChild = new HasChildFilter(filterPhase);
        NodeFilter filterHasSib = new HasSiblingFilter(filterHasChild);
        NodeFilter tdFilter = new TagNameFilter("td");
        NodeList drawRowNodeList;
        StringBuilder stb = new StringBuilder("");
        String result = "";
        try {
            NodeList nodes = parser.extractAllNodesThatMatch(filterHasSib);
            Parser newParser = Parser.createParser(nodes.toHtml(), CharsetConstant.CHARSET_GBK);
            drawRowNodeList = newParser.extractAllNodesThatMatch(tdFilter);
            for (int i = 0; i < drawRowNodeList.size(); i++) {
                Node tdNode = drawRowNodeList.elementAt(i);
                String txt = tdNode.toPlainTextString();
                if (txt != null && !"".equals(txt)) {
                    //先把 A J Q K 转成 1 11 12 13
                    if ("A".equals(txt)) {
                        txt = "01";
                    }
                    if ("J".equals(txt)) {
                        txt = "11";
                    }
                    if ("Q".equals(txt)) {
                        txt = "12";
                    }
                    if ("K".equals(txt)) {
                        txt = "13";
                    }
                    if (txt.length() == 1) { //补零 到两位
                        txt = "0" + txt;
                    }
                } else {
                    Node imgNode = tdNode.getFirstChild();
                    String tempTxt = imgNode.getText();
                    logger.info(tempTxt);
                    if (tempTxt != null && !"".equals(tempTxt) && tempTxt.indexOf(".jpg") > 1) {
                        txt = tempTxt.substring(tempTxt.indexOf(".jpg") - 1,tempTxt.indexOf(".jpg"));
                        if (txt != null && "2".equals(txt)) {  //获取官网的红桃、方块、梅花 的图片序号 与 贵司定义的数值不一致，所以转换
                            txt = "4";
                        } else if (txt != null && "3".equals(txt)){
                            txt = "2";
                        } else if (txt != null && "4".equals(txt)){
                            txt = "3";
                        }
                    }
                }
                stb.append(txt);
                int j = i + 1;
                if (j%2 == 0) {
                    stb.append(",");
                }
            }
            if (!"".equals(stb) && stb.lastIndexOf(",") >0) {
                result = stb.substring(0,stb.lastIndexOf(","));
            }
        } catch (ParserException e) {
            logger.error(e.getMessage(), e);
            logger.error("解析html出错, data={}", data);
        }
        LotteryDraw lotteryDraw = new LotteryDraw();
        lotteryDraw.setLotteryType(lotteryType);
        lotteryDraw.setPhase(phase);
        lotteryDraw.setResult(result);
        logger.info(result);
        return lotteryDraw;
	}

	@Override
	public LotteryDraw fetchResult(String phase) {
		return this.fetchResultDetail(phase);
	}

	@Override
	protected String getResultDetailUrl(String phase) {
        if (StringUtils.isEmpty(phase)) {
            return URL_HISTORY;
        }
        if (phase.length() == 10) {
            return URL_HISTORY;
        }
		return null;
	}

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}
}
